﻿using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Cyss.Core;
using Common.Api.Services;
using Common.Api.Entitys;
using Common.Api.Dtos;
using Cyss.Core.Api.JWT;
using System.Threading.Tasks;
using System.IO;
using Microsoft.AspNetCore.Http;

namespace Common.Api.Controllers
{

    /// <summary>
    /// 获取图片表 Api 接口
    /// </summary>
    public class PictureController : CommonBaseApiController
    {
        #region 初始化
        private readonly PictureService _pictureService;

        public PictureController(PictureService pictureService)
        {
            _pictureService = pictureService;
        }
        #endregion

        #region 图片表增删该查

        /// <summary>
        /// Gets the download binary array
        /// </summary>
        /// <param name="file">File</param>
        /// <returns>
        /// A task that represents the asynchronous operation
        /// The task result contains the download binary array
        /// </returns>
        public virtual async Task<byte[]> GetDownloadBitsAsync(IFormFile file)
        {
            await using var fileStream = file.OpenReadStream();
            await using var ms = new MemoryStream();
            await fileStream.CopyToAsync(ms);
            var fileBytes = ms.ToArray();
            return fileBytes;
        }


        [HttpPost]
        [RequestSizeLimit(int.MaxValue)]
        //do not validate request token (XSRF)
        public virtual async Task<OperateResult<PictureResult>> AsyncUpload([FromForm] IFormCollection formCollection)
        {
            try
            {
                var httpPostedFile = formCollection.Files.FirstOrDefault();
                if (httpPostedFile == null)
                    return OperateResultContent<PictureResult>(false, null, "No file uploaded");

                var _fileProvider = new FileProvider();

                var fileBinary = await GetDownloadBitsAsync(httpPostedFile);
                //_downloadService.GetDownloadBits(httpPostedFile);

                var fileName = httpPostedFile.FileName;
                const string qqFileNameParameter = "qqfilename";
                if (string.IsNullOrEmpty(fileName) && Request.Form.ContainsKey(qqFileNameParameter))
                    fileName = Request.Form[qqFileNameParameter].ToString();
                //remove path (passed in IE)
                fileName = _fileProvider.GetFileName(fileName);

                var contentType = "";

                var fileExtension = _fileProvider.GetFileExtension(fileName);
                if (!string.IsNullOrEmpty(fileExtension))
                    fileExtension = fileExtension.ToLowerInvariant();

                //contentType is not always available 
                //that's why we manually update it here
                //http://www.sfsu.edu/training/mimetype.htm
                if (string.IsNullOrEmpty(contentType))
                {
                    switch (fileExtension)
                    {
                        case ".bmp":
                            contentType = MimeTypes.ImageBmp;
                            break;
                        case ".gif":
                            contentType = MimeTypes.ImageGif;
                            break;
                        case ".jpeg":
                        case ".jpg":
                        case ".jpe":
                        case ".jfif":
                        case ".pjpeg":
                        case ".pjp":
                            contentType = MimeTypes.ImageJpeg;
                            break;
                        case ".png":
                            contentType = MimeTypes.ImagePng;
                            break;
                        case ".tiff":
                        case ".tif":
                            contentType = MimeTypes.ImageTiff;
                            break;
                        default:
                            break;
                    }
                }

                var picture = await _pictureService.InsertPicture(fileBinary, contentType, null);

                //when returning JSON the mime-type must be set to text/plain
                //otherwise some browsers will pop-up a "Save As" dialog.
                var url = await _pictureService.GetPictureUrl(picture, 100);
                return OperateResultContent(true, new PictureResult { PictureId = picture.Id, ImageUrl =  url });
            }
            catch (Exception ex)
            {
                return OperateResultContent<PictureResult>(false, null, ex.Message);
            }

        }

        [HttpGet]
        public virtual async Task<OperateResult<PictureResult>> GetPictureUrlById(int pictureId, int targetSize)
        {
            var url = await _pictureService.GetPictureUrl(pictureId, targetSize);
            return OperateResultContent(true, new PictureResult { ImageUrl = url });
        }

        #endregion
    }
}




